import React, { Component } from 'react';
import { Button, Col, Modal, Popover, Row } from 'antd';
import { messages } from 'share/common';
import ResizeTable from 'components/resize-table';
import 'styles/budget-setting/budget-organization/budget-item/assigment-group.scss';
import budgetOrganizationService
  from 'containers/budget-setting/budget-organization/budget-organnization.service';
import ListSelector from 'components/list-selector';

class AssignmentGroup extends Component {

  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      visible: false,
      data: [],
      buttons: [
        {
          name: messages('budget-setting.key235')/*新增*/,
          params: {
            type: 'primary',
            onClick: this.handleAdd
          }
        },
        {
          name: messages('common.delete')/*删除*/,
          params: {
            type: 'default',
            onClick: this.handleDelete
          }
        },
        {
          name: messages('common.back')/*返回*/,
          params: {
            type: 'default',
            onClick: this.handleBack
          }
        }
      ],
      columns: [
        {
          title: messages('components.key11'/*编码*/),
          dataIndex: 'code',
          width: '30%',
          render: (value) => (
            <Popover
              placement="topLeft"
              content={value}
              overlayStyle={{ maxWidth: 500 }}>
              {value}
            </Popover>)
        },
        {
          title: messages('components.key10'/*名称*/),
          dataIndex: 'name',
          width: '30%',
          render: (value) => (
            <Popover
              placement="topLeft"
              content={value}
              overlayStyle={{ maxWidth: 500 }}>
              {value}
            </Popover>)
        },
        {
          title: messages('components.key12'/*描述*/),
          dataIndex: 'description',
          width: '40%',
          render: (value) => (
            <Popover
              placement="topLeft"
              content={value}
              overlayStyle={{ maxWidth: 500 }}>
              {value}
            </Popover>)
        }
      ]
    };
  }

  handleAdd = () => {
    this.setState({ userGroupVisible: true });
  };

  handleDelete = () => {
    const { selectedRowKeys,data } = this.state;
    let ids = [];
    if (selectedRowKeys[0]) {
      selectedRowKeys.map(item => {
        data.map(ret => {
          if (item === ret.id) {
            ids.push(ret.recordId);
          }
        });
      });
      budgetOrganizationService.deleteUserGroup({ ids: ids.join(',') })
        .then(() => {
          this.setState({ loading: true }, this.getUserGroup);
        });
    }
  };

  handleBack = () => {
    this.setState({ visible: false });
  };

  handleAssignmentGroup = (e) => {
    e.stopPropagation();
    this.setState({ visible: true, loading: true }, this.getUserGroup);
  };

  getUserGroup = () => {
    const { record } = this.props;
    let { data, pagination } = this.state;
    budgetOrganizationService.getUserGroup(record.id)
      .then(res => {
        data = [];
        res.data.forEach(item => {
          data.push({ ...item.userGroup, recordId: item.id });
        });
      })
      .finally(() => {
        this.setState({ loading: false, data, pagination });
      });
  };


  handleUpdate = (value) => {
    const { record: { id } } = this.props;
    let params = { journalTypeId: id, userGroupIds: [] };
    value.result.forEach(item => {
      params.userGroupIds.push(item.id);
    });
    budgetOrganizationService.addUserGroup(params)
      .then(() => {
        this.getUserGroup();
      });
  };

  handleCancel = () => {
    this.setState({ visible: false });
  };

  handleSelectChange = (selectedRowKeys) => {
    this.setState({ selectedRowKeys });
  };

  handleAddUserGroup = (value) => {
    this.setState({ userGroupVisible: false, loading: true }, () => {
      this.handleUpdate(value);
    });
  };

  render() {
    const { visible, buttons, data, loading, columns, selectedRowKeys, userGroupVisible } = this.state;
    const rowSelection = { selectedRowKeys, onChange: this.handleSelectChange };
    const { record = {} } = this.props;
    return (
      <section>
        <a onClick={this.handleAssignmentGroup}>{messages('budget-setting.key236')/*分配人员组*/}</a>
        <Modal
          title={messages('budget-setting.key237')/*人员组*/}
          visible={visible}
          onCancel={this.handleCancel}
          footer={null}>
          <section className="assignment-group">
            <section className="assignment-group-header">
              <Row>
                <Col span={12}>
                  {messages('budget-setting.key99'/*预算日记账类型代码*/)}：
                  {record.journalTypeCode}
                </Col>

                <Col span={12}>
                  {messages('budget-setting.key100'/*预算日记账类型名称*/)}：
                  {record.journalTypeName}
                </Col>
              </Row>
            </section>
            <section className="assignment-group-content">
              <section className="assignment-group-button">
                {buttons.map(item => <Button className="assignment-group-button__button" {...item.params}>{item.name}</Button>)}
              </section>
              <ResizeTable
                size="middle"
                rowKey={'id'}
                columns={columns}
                loading={loading}
                bordered
                dataSource={data}
                rowSelection={rowSelection}/>
            </section>
          </section>
        </Modal>

        <ListSelector
          visible={userGroupVisible}
          type="user_group"
          valueKey="id"
          labelKey="name"
          selectedData={data}
          onOk={this.handleAddUserGroup}
          onCancel={() => {this.setState({ userGroupVisible: false });}}/>
      </section>
    );
  }
}

AssignmentGroup.propTypes = {
  className: React.PropTypes.string,
  record: React.PropTypes.object
};

export default AssignmentGroup;
